
#include "lib_xml.h"





int xml_xpath_parse_context(void)
{
    // 解析 HTML 文档
    const char* html = "<html><body><h1>Hello World!</h1></body></html>";
	
    htmlDocPtr doc = htmlReadMemory(html, strlen(html), NULL, NULL, HTML_PARSE_NOWARNING | HTML_PARSE_NOERROR);

    // 编译 XPath 表达式
    xmlXPathContextPtr context = xmlXPathNewContext(doc);
    xmlXPathObjectPtr result = xmlXPathEvalExpression(BAD_CAST "/html/body/h1", context);

    // 输出匹配结果
    if (result) {
        for (int i = 0; i < result->nodesetval->nodeNr; i++) {
            xmlNodePtr node = result->nodesetval->nodeTab[i];
            if (node->type == XML_ELEMENT_NODE) {
                log_i("%s\n", node->name);
            }
        }
        xmlXPathFreeObject(result);
    }

    // 释放资源
    xmlXPathFreeContext(context);
    xmlFreeDoc(doc);
    xmlCleanupParser();

    return 0;
}



int xml_xpath_parse_file(void) 
{
    xmlDocPtr doc;
    xmlXPathContextPtr xpathCtx;
    xmlXPathObjectPtr xpathObj;

    // 加载HTML文档
    doc = htmlReadFile("./五星红旗迎风飘扬2-电视剧-全集-高清正版在线观看-bilibili-哔哩哔哩.html", NULL, HTML_PARSE_RECOVER);

    // 创建XPath上下文
    xpathCtx = xmlXPathNewContext(doc);

    // 使用XPath查询元素
    xpathObj = xmlXPathEvalExpression((const xmlChar*)"//div[@class='bili-avatar']", xpathCtx);

    // 遍历查询结果
    xmlNodeSetPtr nodes = xpathObj->nodesetval;
    for (int i = 0; i < nodes->nodeNr; i++) {
        xmlNodePtr node = nodes->nodeTab[i];
        if (node->type == XML_ELEMENT_NODE) {
            log_i("Element name: %s\n", node->name);
            xmlChar* text = xmlNodeGetContent(node);
            log_i("Element content: %s\n", text);
            xmlFree(text);
        }
    }

    // 释放资源
    xmlXPathFreeObject(xpathObj);
    xmlXPathFreeContext(xpathCtx);
    xmlFreeDoc(doc);

    return 0;
}


